package com.niodata.dp.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapUtils {

  /**
   * convert map to flatten map.
   * @param map map
   * @param flatArray flat array or not
   * @return flatten map
   */
  public static Map<String, Object> toFlattenMap(Map<String, Object> map, boolean flatArray) throws IOException {
    Map<String, Object> resMap = new HashMap<>();
    objectToFlatMap(map, "", resMap, flatArray);
    return resMap;
  }

  static void objectToFlatMap(Object value, String key, Map<String, Object> resMap, boolean flatArray)
      throws IOException {
    if (value == null) {
      resMap.put(key, null);
    } else if (Map.class.isAssignableFrom(value.getClass())) {
      Map<String, Object> valueMap = (Map<String, Object>) value;
      Set<String> keys = valueMap.keySet();
      for (String k : keys) {
        Object v = valueMap.get(k);
        String newKey = key.length() == 0 ? k : key + "." + k;
        objectToFlatMap(v, newKey, resMap, flatArray);
      }
    } else if (List.class.isAssignableFrom(value.getClass())) {
      if (flatArray) {
        List list = (List) value;
        for (int i = 0; i < list.size(); i++) {
          String k = "[" + i + "]";
          String newKey = key.length() == 0 ? k : key + k;
          objectToFlatMap(list.get(i), newKey, resMap, flatArray);
        }
      } else {
        resMap.put(key, JsonUtil.toJson(value));
      }
    } else {
      resMap.put(key, value);
    }
  }
}
